<?php
namespace app\backend\controller;

class Staff extends Backend {
	
	public function index() {
		
		$view = \think\View::instance();
		$request = \think\Request::instance();
		
		$where = array();
		$where['staff.is_del'] = 0;
		$condition = array();
		$condition['realname'] = $request->get('realname', '');
		if(0 < mb_strlen($condition['realname'], 'utf8')){
			$where['staff.realname'] = array('like', '%%'.$condition['realname'].'%%');
		};
		$view->assign('condition', $condition);
		
		$order_number = \app\common\model\RecycleOrderModel::field('COUNT(`recycle_order`.`id`)')->where('`recycle_order`.`staff_id` = `staff`.`id`')->buildsql();
		$field = array(
			'`staff`.*',
			$order_number . ' AS `order_number`'
		);
		$banner_select = \app\common\model\StaffModel::field($field)
			->where($where)->order('staff.id DESC')->paginate(10, false, array('query'=>$condition));
		$view->assign('page', $banner_select->render());
		
		$data_list = array();
		foreach($banner_select as $StaffModel){
			$data = $StaffModel->toArray();
			$data_list[] = $data;
		};
		$view->assign('data_list', $data_list);
		
		unset($where, $condition, $field, $banner_select, $StaffModel);
		return $view->fetch();
		
	}
	
	public function del() {
		
		$parameter = \think\Request::instance()->post();
		$judge_1 = array_key_exists('id', $parameter) && is_integer($parameter['id']) && (0 < $parameter['id']);
		if(!$judge_1){
			return $this->disposeJson(1, '参数校验失败');
		};
		
		$StaffModel = \app\common\model\StaffModel::get($parameter['id']);
		if((null === $StaffModel) || (1 === $StaffModel->getData('is_del'))){
			return $this->disposeJson(1, '目标不存在，请刷新后重试');
		};
		
		$SubscriberModel = \app\common\model\SubscriberModel::where('staff_id', $StaffModel->id)->find();
		if(null === $SubscriberModel){
			return $this->disposeJson(1, '对应的用户不存在，请联系管理员');
		};
		
		\app\common\model\Model::startTrans();
		try{
			
			// 解绑用户
			$result = \app\common\model\SubscriberModel::where('id', $SubscriberModel->id)->update(['staff_id' => 0]);
			if(1 !== $result){
				throw new \Exception('解绑用户失败');
			};
			
			// 修改员工状态
			$StaffModel->is_del = 1;
			$result = $StaffModel->save();
			if(false == $result){
				throw new \Exception('修改员工状态失败');
				return $this->disposeJson(1, '');
			};
			
			// 修改申请状态
			$result = \app\common\model\StaffApplyModel::where('subscriber_id', $SubscriberModel->id)->update(['result' => 2]);
			if(1 !== $result){
				throw new \Exception('修改申请状态失败');
			};
			
			\app\common\model\Model::commit();
			
		}catch(\Exception $error){
			
			\app\common\model\Model::rollback();
			$message = is_string($error->getMessage()) ? $error->getMessage() : json_encode($error->getMessage());
			return $this->disposeJson(1, $message);
			
		};
		
		return $this->disposeJson(0, '操作成功，即将跳转');
	}
	
	public function edit_region() {
		
		$request = \think\Request::instance();
		
		$staff_id = $request->get('staff_id');
		$judge_1 = is_string($staff_id) && (1 === preg_match('/^[0-9]{1,10}$/', $staff_id)) && settype($staff_id, 'integer') && (0 !== $staff_id);
		if(true === $request->isAjax()){
			
			$parameter = $request->post();
			$judge_1 = array_key_exists('cancel_id', $parameter) && is_array($parameter['cancel_id']);
			$judge_2 = array_key_exists('checked_id', $parameter) && is_array($parameter['checked_id']);
			if(!$judge_1 || !$judge_2){
				return $this->disposeJson(1, '参数校验失败');
			};
			
			if((0 === count($parameter['cancel_id'])) && (0 === count($parameter['checked_id']))){
				return $this->disposeJson(1, '选中与取消参数不能同时为空');
			};
			$cancel_list = array();
			foreach($parameter['cancel_id'] as $id){
				$judge_1 = is_integer($id) && (0 < $id);
				if(!$judge_1){
					return $this->disposeJson(1, '取消参数校验失败');
				};
				if(in_array($id, $cancel_list)){
					return $this->disposeJson(1, '取消参数存在重复');
				};
				$cancel_list[] = $id;
			};
			$checked_list = array();
			foreach($parameter['checked_id'] as $id){
				$judge_1 = is_integer($id) && (0 < $id);
				if(!$judge_1){
					return $this->disposeJson(1, '选中参数校验失败');
				};
				if(in_array($id, $checked_list)){
					return $this->disposeJson(1, '取消参数存在重复');
				};
				$checked_list[] = $id;
			};
			
			// 校验已取消的数据
			$cancel_list = array();
			$judge_select = \app\common\model\StaffRegionModel::where('staff_id', $staff_id)->where('region_id', 'in', $parameter['cancel_id'])->select();
			foreach($judge_select as $StaffRegionModel){
				$cancel_list[] = $StaffRegionModel->id;
			};
			
			// 校验已选中的数据
			$checked_list = array();
			$judge_select = \app\common\model\RegionModel::field(['id'])->where('grade', 3)->where('id', 'in', $parameter['checked_id'])->select();
			if(count($parameter['checked_id']) !== count($judge_select)){
				return $this->disposeJson(1, '选中参数同步校验失败');
			};
			$judge_select = \app\common\model\StaffRegionModel::where('staff_id', $staff_id)->where('region_id', 'in', $parameter['checked_id'])->select();
			foreach($parameter['checked_id'] as $id){
				$judge = true;
				foreach($judge_select as $StaffRegionModel){
					if($id === $StaffRegionModel->region_id){
						$judge = false;
						break;
					};
				};
				if(true === $judge){
					$checked_list[] = $id;
				};
			};
			
			if((0 === count($cancel_list)) && (0 === count($checked_list))){
				return $this->disposeJson(1, '没有更改');
			};
			
			\app\common\model\Model::startTrans();
			try{
				
				// 移除绑定的地区
				if(0 < count($cancel_list)){
					$result = \app\common\model\StaffRegionModel::where('id', 'in', $cancel_list)->delete();
					if($result !== count($cancel_list)){
						throw new \Exception('移除绑定的地区失败');
					};
				};
				
				// 绑定新的地区
				if(0 < $checked_list){
					$StaffRegionModel = new \app\common\model\StaffRegionModel();
					$insert_list = array();
					foreach($checked_list as $region_id){
						$insert_list[] = array(
							'staff_id' => $staff_id,
							'region_id' => $region_id,
						);
					};
					$result = $StaffRegionModel->saveAll($insert_list);
					if(count($result) !== count($checked_list)){
						throw new \Exception('绑定新的地区失败');
					};
				};
				
				// 结束操作
				\app\common\model\Model::commit();
				
			}catch(\Exception $error){
				
				\app\common\model\Model::rollback();
				$message = is_string($error->getMessage()) ? $error->getMessage() : json_encode($error->getMessage());
				return $this->disposeJson(1, $message);
				
			};
			
			return $this->disposeJson(0, '操作成功，即将刷新');
			
			
		}else{
			
			$view = \think\View::instance();
			
			if(!$judge_1){
				return $this->disposeHtml('参数校验失败', $view);
			};
			
			$where = array();
			$condition = array();
			$condition['staff_id'] = $staff_id;
			$condition['title'] = $request->get('title', '');
			if(0 < strlen($condition['title'])){
				$where['region.name_full'] = array('like', '%%'.$condition['title'].'%%');
			};
			
			$staff_count = \app\common\model\StaffRegionModel::field('COUNT(`staff_region`.`id`)')->where('`staff_region`.`region_id` = `region`.`id`')->buildsql();
			$field = array(
				'`region`.*',
				'IFNULL(`staff_region`.`id`, 0) AS `is_checked`',
				$staff_count . ' AS `staff_count`',
			);
			$region_select = \app\common\model\RegionModel::field($field)
				->join('staff_region', '`staff_region`.`region_id` = `region`.`id` AND `staff_region`.`staff_id` = '.$staff_id, 'LEFT')
				->where('region.grade', 3)
				->where($where)
				->order('is_checked DESC')
				->paginate(10, false, array('query'=>$condition));
			$view->assign('page', $region_select->render());
			
			$region_list = array();
			foreach($region_select as $RegionModel){
				$region_list[] = $RegionModel->toArray();
			};
			$view->assign('region_list', $region_select);
			
			$view->assign('staff_id', $staff_id);
			
			$view->assign('condition', $condition);
			
			return $view->fetch();
			
		};
		
	}
	
}